/*
 * ModuleService.java
 *
 * Copyright 2012 the original author or authors(ninglong).
 *
 * Licensed under the org.geek.module.service.impl, Version 1.0 (the "License");
 *
 */
package org.geek.app.module.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.geek.app.module.service.IModuleService;
import org.geek.core.base.BaseException;
import org.geek.core.bean.ExtTree;
import org.geek.core.mybatis.domain.Criteria;
import org.geek.core.mybatis.domain.Module;
import org.geek.core.mybatis.mapper.ModuleMapper;
import org.springframework.stereotype.Service;

/**
 * <p></p>
 * @author ninglong bhd2973@qq.com
 * @version V1.0
 */
@Service
public class ModuleService implements IModuleService {

	@Resource
	private ModuleMapper moduleMapper;

	@Override
	public List<ExtTree> getModules2Tree() {
		Criteria criteria = new Criteria();
		List<Module> list = this.getModuleByCriteria(criteria);
		List<ExtTree> trees = new ArrayList<ExtTree>();
		for(Module module : list){
			ExtTree tree = new ExtTree();
			tree.setId(module.getModuleId());
			tree.setIconCls(module.getIconCss());
			tree.setName(module.getModuleName());
			tree.setText(module.getModuleName());
			tree.setParentId(module.getParentId());
			tree.setUrl(module.getModuleUrl());
			trees.add(tree);
		}
		return trees;
	}

	@Override
	public int countModuleByCriteria(Criteria criteria) {
		return moduleMapper.countModuleByCriteria(criteria);
	}

	@Override
	public List<Module> getModuleByCriteria(Criteria criteria) {
		return moduleMapper.getModuleByCriteria(criteria);
	}

	@Override
	public int addModule(Module module) {
		return moduleMapper.addModule(module);
	}
	
	@Override
	public int modModule(Module module) {
		if(module.getModuleId()==module.getParentId()){
			throw new BaseException("父级菜单选择错误！");
		}
		return moduleMapper.modModule(module);
	}
	
	@Override
	public int delModuleByModuleId(int moduleId) {
		int i = moduleMapper.delModuleByModuleId(moduleId);
		i = i + moduleMapper.delModuleAndRoleByModuleId(moduleId);//删除模块后，将t_role_module中与该模块有关的数据删除
		return i;
	}
	
	@Override
	public List<ExtTree> getModuleByAuth(int userId){
		List<ExtTree> trees = new ArrayList<ExtTree>();
		List<Module> list = moduleMapper.getModuleByAuth(userId);
		if(list!=null){
			for(Module module : list){
				ExtTree tree = new ExtTree();
				tree.setId(module.getModuleId());
				tree.setIconCls(module.getIconCss());
				tree.setName(module.getModuleName());
				tree.setText(module.getModuleName());
				tree.setParentId(module.getParentId());
				tree.setUrl(module.getModuleUrl());
				trees.add(tree);
			}
		}
		return trees;
	}
}